package com.caregiver.watch.business.care.service.strategy.impl;

import com.alibaba.fastjson2.JSON;
import com.caregiver.watch.business.care.dao.HealthAlertConfigDao;
import com.caregiver.watch.business.care.enums.AgeGroupEnum;
import com.caregiver.watch.business.care.enums.HealthAlertTypeEnum;
import com.caregiver.watch.business.care.model.bo.AlertMessageBo;
import com.caregiver.watch.business.care.model.bo.HeartRateWarningConfig;
import com.caregiver.watch.business.care.model.po.HealthAlertConfig;
import com.caregiver.watch.business.care.service.UserAlertRecordService;
import com.caregiver.watch.business.care.service.UserPackageOrderService;
import com.caregiver.watch.business.care.service.strategy.AbstractHealthWarningStrategy;
import com.caregiver.watch.business.data.protobuf.AlarmInfo;
import com.caregiver.watch.business.data.utils.time.DateTimeUtils;
import com.caregiver.watch.business.user.model.po.UserCareRecipient;
import com.caregiver.watch.business.user.service.UserDeviceService;
import com.caregiver.watch.common.utils.time.DateUtils;
import com.caregiver.watch.thirdparty.service.JPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.caregiver.watch.business.user.helper.CareRecipientHelper.calculateAge;
import static com.caregiver.watch.common.constant.NumberConstants.ONE;
import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

/**
 * @Description: 心率预警策略
 * @Author 疆戟
 * @Date 2025/10/26 12:48
 * @Version 1.0
 */
@Component
@Slf4j
public class HeartRateWarningStrategy extends AbstractHealthWarningStrategy<List<AlarmInfo.HrAlarmV3>> {


    private final UserPackageOrderService userPackageOrderService;

    public HeartRateWarningStrategy(UserDeviceService userDeviceService,
                                    HealthAlertConfigDao healthAlertConfigDao,
                                    UserPackageOrderService userPackageOrderService,
                                    UserAlertRecordService userAlertRecordService,
                                    JPushService jPushService) {
        super(userDeviceService, healthAlertConfigDao, userAlertRecordService, jPushService);
        this.userPackageOrderService = userPackageOrderService;
    }

    @Override
    public HealthAlertTypeEnum getAlertType() {
        return HealthAlertTypeEnum.HEART_RATE_WARNING;
    }

    @Override
    public void handle(Long userId, String deviceUuId, List<AlarmInfo.HrAlarmV3> data) {
        log.info("处理心率预警：{}", data);
        if (CollectionUtils.isEmpty(data)) {
            log.warn("未获取到心率数据");
            return;
        }
        HealthAlertConfig config = getConfig();
        if (Objects.isNull(config)) {
            log.warn("未配置心率预警");
            return;
        }
        if (BooleanUtils.isNotTrue(config.getEnabled())) {
            log.warn("心率预警未启用");
            return;
        }
        String alertConfig = config.getAlertConfig();
        log.info("心率预警配置：{}", alertConfig);
        if (StringUtils.isBlank(alertConfig)) {
            log.warn("未配置心率预警");
            return;
        }
        // 获取被关照人
        UserCareRecipient userCareRecipient = queryContactDeviceDetail(userId, deviceUuId);
        if (Objects.isNull(userCareRecipient)) {
            log.warn("未查询到被关照人");
            return;
        }
        List<HeartRateWarningConfig> heartRateWarningConfigs = JSON.parseArray(alertConfig, HeartRateWarningConfig.class);
        if (CollectionUtils.isEmpty(heartRateWarningConfigs)) {
            log.warn("未配置心率预警");
            return;
        }
        // 获取告警中的最低心率
        Optional<AlarmInfo.HrAlarmV3> minHrOption = data.stream().filter(alarmInfo -> alarmInfo.hasHr()).min(Comparator.comparingInt(AlarmInfo.HrAlarmV3::getHr));
        if (!minHrOption.isPresent()) {
            log.warn("未获取到心率");
            return;
        }
        AlarmInfo.HrAlarmV3 hrAlarm = minHrOption.get();
        int minHr = hrAlarm.getHr();
        // 获取配置
        Optional<HeartRateWarningConfig> first = heartRateWarningConfigs.stream()
                .filter(warningConfig -> {
                    Integer maxHeartRate = warningConfig.getMaxHeartRate();
                    if (Objects.isNull(maxHeartRate)) {
                        return false;
                    }
                    Integer minHeartRate = Optional.ofNullable(warningConfig.getMinHeartRate()).orElse(ZERO);
                    return minHr >= minHeartRate && minHr < maxHeartRate;
                })
                .findFirst();
        // 获取配置
        if (!first.isPresent()) {
            return;
        }
        HeartRateWarningConfig warningConfig = first.get();
        log.info("心率预警配置：{}", warningConfig);
        // 扣除告警次数
        if (!userPackageOrderService.deductWarningCount(userId, ONE)) {
            log.warn("扣除心率预警次数失败 userId:{}", userId);
            return;
        }
        // 获取告警时间
        LocalDateTime alarmTime = DateUtils.convert2LocalDateTime(hrAlarm.getTimeStamp().getDateTime().getSeconds());
        log.info(String.format("hr warn time:%s, hr:%d", alarmTime, hrAlarm.getHr()));
        AlertMessageBo alertMessage = AlertMessageBo.build(warningConfig.getWarningTitle(), String.valueOf(minHr), warningConfig.getThreshold(), warningConfig.getHandleSuggestions());
        // 发送告警
        Boolean sendPush = sendPush(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, alertMessage);
        if (BooleanUtils.isTrue(sendPush)) {
            // 记录告警
            saveAlertRecord(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, JSON.toJSONString(alertMessage));
        }
    }
}
